package com.itclass.auth.handler.authentication.support;

import com.itclass.auth.authentication.token.AbstractForwardAuthenticationToken;

import com.itclass.auth.authentication.token.supprt.GitHubLoginAuthenticationToken;
import com.itclass.auth.constant.RedisCacheKeyConstants;
import com.itclass.auth.handler.authentication.AbstractAuthenticationSuccessHandler;
import com.itclass.auth.util.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Component
public class ForwardAuthenticationSuccessHandler  extends AbstractAuthenticationSuccessHandler {

    @Override
    public boolean supports(Class<?> authentication) {
        return AbstractForwardAuthenticationToken.class.isAssignableFrom(authentication)&& GitHubLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        GitHubLoginAuthenticationToken gitHubLoginAuthenticationToken = (GitHubLoginAuthenticationToken) authentication;
        StringBuilder sb = new StringBuilder();
        sb.append("/loading.html?token=");
        sb.append(request.getAttribute(RedisCacheKeyConstants.AUTHORIZATION));
        sb.append("&loginName=");
        String name = gitHubLoginAuthenticationToken.getDetails().getName();
        if (StringUtils.isNotEmpty(name)) {
            sb.append(URLEncoder.encode(name, StandardCharsets.UTF_8.name()));
        }
        sb.append("&code=200");
        sb.append("&loginAccount=");
        sb.append(URLEncoder.encode(gitHubLoginAuthenticationToken.getDetails().getUsername(), StandardCharsets.UTF_8.name()));
        // 重定向
        response.sendRedirect(sb.toString());
    }
}
